#!/usr/bin/python

"""Tests the functionality of the select ripple."""

from __future__ import division, print_function

import argparse
import random
import sys
import threading
import time

from lib import circuit
from lib import ripple

def main():
  parser = argparse.ArgumentParser()
  parser.add_argument("-d", "--add_default",
                      help="add a default case",
                      action="store_true", default=False)
  args = parser.parse_args()

  langdir = circuit.local_lang()

  chan1 = ripple.Chan(langdir)
  chan1.set_cap(0)

  def send_on_chan1():
    name = threading.current_thread().name
    s = random.randrange(0, 3)
    print("Thread {!r} sleeping {}".format(name, s))
    time.sleep(s)
    print("Thread {!r} sending on chan1".format(name))
    chan1.send("chan1 says 'hi' to select", timeout=5)

  chan2 = ripple.Chan(langdir)
  chan2.set_cap(0)

  def recv_on_chan2():
    name = threading.current_thread().name
    s = random.randrange(0, 3)
    print("Thread {!r} sleeping {}".format(name, s))
    time.sleep(s)
    print("Thread {!r} receiving on chan2".format(name))
    val = chan2.recv(timeout=5)
    print("Thread {!r} received {!r}".format(name, val))

  sel = ripple.Select(langdir)
  cases = [(chan1.recv_path, None),
           (chan2.send_path, "select says 'hi' to c2")]
  if args.add_default:
    cases.append(ripple.Select.DefaultCase)
  print("Cases:\n")
  for case in cases:
    print(case)

  threads = [threading.Thread(name="chan1", target=send_on_chan1),
             threading.Thread(name="chan2", target=recv_on_chan2)]

  for t in threads:
    t.daemon = True
    t.start()

  sel.set_cases(cases)
  print(sel.cases())

  print("Selecting {}:".format(sel))
  print("Select received {!r}".format(sel.select()))

  print("Waiting for other channels to time out")


if __name__ == '__main__':
  main()
